import json
from os.path import isfile, exists
from todo import Todo


class TodoStorage:
    def __init__(self):
        self.todo_list = [
            Todo('学习 Flask'), Todo("编写 Todo 单机版"), Todo("编写 Todo HTTP 网络版")
        ]

    def load(self, filename="todos.json"):

        # 检查是否存在文件，若不存在，不继续读了
        if not exists(filename) or not isfile(filename):
            return

        content = ''
        with open(filename, 'r') as f:
            content = f.read()

        data = json.loads(content)
        # print('load data:', data)
        if 'todos' in data and 'current_id' in data:
            self.todo_list = [Todo(**x) for x in data['todos']]
            Todo.current_todo_id = data['current_id']

    def save(self, filename="todos.json"):
        """
        保存的格式如下：
        {
            "current_id": 1,
            "todos": [...]
        }
        """
        data = dict(current_id=Todo.current_todo_id, todos=[x.__dict__ for x in self.todo_list])
        file_content = json.dumps(data, ensure_ascii=False, indent=2)
        with open(filename, "w") as f:
            f.write(file_content)
        pass

    def create(self, title: str):
        todo = Todo(title)
        self.todo_list.append(todo)
        self.save()
        return todo

    def get_list(self):
        return self.todo_list

    def get_by_id(self, todo_id):
        for x in self.todo_list:
            if x.id == todo_id:
                return x

    def mark_completed(self, todo_id):
        todo = self.get_by_id(todo_id)
        if todo is not None:
            todo.completed = True
            self.save()
        return todo
tm=TodoStorage()
tm.load()
tm.save()